package com.witframework.datasource;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

import org.apache.log4j.Logger;

public class SmartProxyConnectionHandle implements InvocationHandler { 
	
	private static  Logger logger = Logger.getLogger(SmartProxyConnectionHandle.class);	
    /**
     * 真实的Connection存储
     */
    protected ConnectionLeakEvent clv=null;
    /**
     * 构造器
     */
    protected SmartProxyConnectionHandle(ConnectionLeakEvent clv) {
        this.clv=clv;
        //this.proxyDataSource=proxyDataSource;
    }
    /**
     * 从InvocationHandler中获取代理连接对象的Connection接口，以便被客户端调用。
     */
    protected Connection newProxyConnection() {
        Class[] interfaces=new Class[1];
        interfaces[0]=java.sql.Connection.class;
        Object o=Proxy.newProxyInstance(clv.getRealConnection().getClass().getClassLoader(),interfaces,this);        
        if (! (o instanceof Connection)) {  //对Tomcat的特殊处理
            o=Proxy.newProxyInstance(clv.getRealConnection().getClass().getSuperclass().getClassLoader(),clv.getRealConnection().getClass().getSuperclass().getInterfaces(),this);
        }        
        Connection proxyConnection=(Connection)o;        
        return proxyConnection;
    }
    /**
     * 动态调用的拦截
     */
    public Object invoke(Object proxy, Method m, Object[] args) throws Exception{
        try {
            Object oReturn=null;
            if (m.getName().equals("close")) {
            	SmartDataSource.closeConnection(this);
            }else{
            	oReturn=m.invoke(clv.getRealConnection(),args);
            }
            return oReturn;
        }catch (Exception ex) {
            if (ex instanceof RuntimeException) {
                throw (RuntimeException) ex;
            } else {
                throw new RuntimeException(ex);
            }            
        }
    }
//    public void finalize(){       
//        try {
//            if (!this.clv.getRealConnection().isClosed()) {
//            	logger.warn("**  CRM. release a leaked connection.");
//            	SmartDataSource.closeConnection(this);
//            }                
//        }catch (java.sql.SQLException ex) {
//           
//        }catch(Exception e){
//        	 e.printStackTrace();
//        }
//   }
}